/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, Table, TableBody, TableRow, Cell, CCell, Button, Collapse, TableHead, useTheme,
} from "customize-easy-ui-component";
import { DirectLink } from "../../../routing/Link";
import {ReportViewProps, ReportViewSubProps,} from "../../common/base";
import {分项末尾链接,} from "../../common/rarelyVary";
import {useMainRepUrlOr, useSplitSubCapacity, useSplitSubRepList} from "../../hook/useMainRepUrlOr";
import {useContext} from "react";
import RoutingContext from "../../../routing/RoutingContext";
import {useThreeColumnSubr} from "../../hook/useThreeColumnSubr";
import {config汇总, config测量, config测量仪,} from "./Detection.O-1";
import {Each_ZdSetting, useContent2hTableViewer, useRep2hTableViewer} from "../../hook/useRepTableEditor";
import {floatInterception} from "../../../common/tool";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";

/**@param fxIdx: 独立流转模式的 分项序号的基数； 若是嵌入式的分项该参数=undefined! rep?.id!==repId
 * 只要是公共的模板：那modelConfigs.ts就不能少了配置该模板代码。
 * */
export const ReportView: React.FunctionComponent<ReportViewProps> = (
    {repId,   source: parentOrc,  verId,rep, redId,fxIdx ,...other}
) => {
    const {urlMainRep}=useMainRepUrlOr(rep);
    const lsBlockMax=useSplitSubCapacity(parentOrc?._SWELLING_MS?.length,1);       //【模板敲定一次性最大几个分项显示出来】有些分项报告模板可能存在很多个分项 最多1个
    const {sumArea, areaIdAs, btnBindUses}=useSplitSubRepList(parentOrc?._SWELLING_MS ?? [], lsBlockMax,false);
    const { get:getRouteUrl } = useContext(RoutingContext);
    const routeLevels=getRouteUrl().entries.length;
    const routeTemplate=getRouteUrl().entries[routeLevels-1]?.routeData?.params?.template;
    return (
        <React.Fragment>
          <div  id="rp_swelling_ms_"  css={{"@media not print": {marginTop:'1rem', marginBottom: '1rem'},}}>
             <DirectLink  href={`/report/SWELLING_MS/ver/${verId}/${repId}/SWELLING_MS/_Controller`}>
                <div css={{"@media print":{display: 'none'} }}>
                    <Button>{(repId===rep?.id && rep?.modeltype!=='SWELLING_MS')? '内嵌式的':'独立流转的'}胀粗测量报告分项控制器</Button>
                </div>
             </DirectLink>
            {(new Array(sumArea).fill(null)).map((s:any,ak:number) => {
                const [isDisplay, bindBtn]=btnBindUses[ak];      //不要加上 tabIndex={0} 超过折叠区域最大数量的？
                //可折叠区的：独立流转的报告，和内嵌分项的，实际还分开的。两者独自控制折叠的。内嵌分项rep.id相等，独立流转的却不等的ID;
                return <React.Fragment key={ak}>
                    <div key={ak} role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                        { <Text variant="h4">{`胀粗测量折叠区${ak+1}，`}{isDisplay ? `收起`:`更多..`}</Text> }
                    </div>
                    <Collapse id={`${ak}`} show={isDisplay} noAnimated>
                        { areaIdAs[ak]?.map((surpId: any, m:number) => {
                            const dispIdx=(fxIdx??0) +(m+ ak*lsBlockMax);
                            return <OneSubRepView key={m} fxIdx={fxIdx} dispIdx={dispIdx} rep={rep} repId={repId}
                                                  verId={verId} parentOrc={parentOrc} surpId={surpId}/>
                        }) }
                        <div role="button" {...bindBtn}  css={{"@media print":{display: 'none'}}}>
                            <Text variant="h4">{`胀粗测量折叠区${ak+1}结束,收起`}</Text>
                        </div>
                    </Collapse>
                </React.Fragment>
            })}
          </div>
          {分项末尾链接({template:'SWELLING_MS', repId: repId||'',verId,urlMainRep,
                nestIn:'SWELLING_MS'!==routeTemplate, flowNest: repId!==rep?.id}) }
       </React.Fragment>
    );
}
//增加自动计算的字段：A平均  z胀粗比率；
const config测量Ext=[...config测量.slice(0,3),  ['','A',0], ...config测量.slice(3), ['','z',0]]  as Each_ZdSetting[];
/**@param fxIdx: 独立流转模式的 分项序号的基数； 若是嵌入式的分项该参数=undefined! rep?.id!==repId
 * 【分项表格】 【分项助手】 可重复分项  JSON.parse(parentOrc?._tblFixed??'[]')   【分项工具】 非主报告底下的。
 * */
const OneSubRepView: React.FunctionComponent<ReportViewSubProps> = (
    {fxIdx,dispIdx,rep,repId,verId,parentOrc,surpId}
) => {
    const theme= useTheme();
    const orc=parentOrc['_SWELLING_MS_'+surpId];
    const [firstNode,_S]=useThreeColumnSubr({orc, config:config测量仪,parentOrc,slash:true,
        href:`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/Instrument`});
    const [renderRows,titleRow]=useRep2hTableViewer(config汇总, '汇总表', orc,false,true,true);
    //多出2列 汇总计算：生成新的表格
    const content= React.useMemo(()=>orc?.测量表?.map((o: any)=>{
        o.A= (Number(o?.f) + Number(o?.s))/2;
        const baseD=Number(o?.G);
        o.z= floatInterception(100*(o?.A-baseD)/baseD, 2);
        return o;
        }), [orc?.测量表]);
    const [render测量,]=useContent2hTableViewer(config测量Ext, content,false,true,true);
    return <React.Fragment>
        <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
            <Text variant="h2" css={{
                textAlign: 'center', marginTop: '1rem',
            }}>胀粗测量报告{dispIdx ? '-' + dispIdx : ''}</Text>
            <div css={{
                display: 'flex',
                justifyContent: 'space-between'
            }}>
                <Text></Text>
                <Text>报告编号：{rep.isp.no}</Text>
            </div>
        </div>
        <Table fixed={ ["9%","25%","13%","22%","12.1%","%"] } tight miniw={800}
                  css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}}>
            <TableBody>
                {firstNode}
            </TableBody>
        </Table>
        <Table fixed={ ["13%","7%","22%","8%","13%","7%","%","9%"] } tight miniw={800}
                         css={{borderCollapse: 'collapse', }}>
                <TableHead>
                    <DirectLink href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/PartSummary`}>
                        {titleRow}
                    </DirectLink>
                </TableHead>
                <TableBody>
                    <DirectLink href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/PartSummary`}>
                       {renderRows}
                    </DirectLink>
                </TableBody>
        </Table>
        <Table fixed={ ["62%","%"]  }  css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableBody>
                <DirectLink  href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/ResultDiagram`}>
                    <TableRow>
                        <Cell colSpan={2} split={true} css={{"@media print": {height: undefined}, padding: 0}}>
                            <div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                                <Text css={{fontSize: '0.8rem'}}>检查部位示意图：</Text><br/>
                                {orc?.示图说明}
                            </div>
                            {orc?._FILE_S部位?.map(({name, url}: any, i: number) => {
                                return <div key={i} css={{"@media print": {pageBreakInside: 'avoid'}}}>
                                    {i > 0 && <hr/>}
                                    <div css={{display: 'flex', justifyContent: 'space-around', alignItems: 'center',}}>
                                        {url &&
                                            <img src={process.env.REACT_APP_OSS_ENDP + url} alt={url}
                                                 css={{
                                                     maxHeight: '14cm',   //在这个元素的上一级元素可以自己加一个固定高度值，就像一张纸打印的应该多高的取值。这个用固定高度会导致图片自动的横竖比例不均衡压缩=会变形啊！24cm是纸张大约最多高度=报告最大图片高。
                                                     maxWidth: '-webkit-fill-available',
                                                     [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},           //普通图片+大屏幕限制高度才是关键的。
                                                     "@media print": {maxHeight: '86vh', maxWidth: '100%'},        //对A4纸张竖版的高度26cm基本都是图片整张纸，这里没考虑多个图片在宽度方向上的并排布局：可用软件合并。
                                                 }}
                                            />
                                        }
                                    </div>
                                </div>
                            })}
                          <div css={{textAlign: 'right'}}>（单位：mm）</div>
                        </Cell>
                    </TableRow>
                </DirectLink>
            </TableBody>
        </Table>
        <Table fixed={ ["8%","9%","9%","10%","8%","6%","%","9%","9%","10%","8%","6%"] } tight miniw={800}
                   css={{borderCollapse: 'collapse', }}>
            <TableHead>
              <DirectLink href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/EvaluationForm`}>
                <TableRow>
                    <CCell rowSpan={2}>测点编号</CCell><CCell colSpan={3}>外径（mm）</CCell>
                    <CCell rowSpan={2}>公称外径（mm）</CCell><CCell rowSpan={2}>胀粗量%</CCell>
                    <CCell rowSpan={2}>测点编号</CCell><CCell colSpan={3}>外径（mm）</CCell>
                    <CCell rowSpan={2}>公称外径（mm）</CCell><CCell rowSpan={2}>胀粗量%</CCell>
                </TableRow>
                <TableRow><CCell>1</CCell><CCell>2</CCell><CCell>平均值</CCell><CCell>1</CCell><CCell>2</CCell><CCell>平均值</CCell>
                </TableRow>
              </DirectLink>
            </TableHead>
            <TableBody>
                <DirectLink href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/EvaluationForm`}>
                    {render测量}
                </DirectLink>
            </TableBody>
        </Table>
        <TailMenRowIspCheck orc={orc} rep={rep} href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/ResultDiagram`}>
            <DirectLink href={`/report/SWELLING_MS/ver/${verId}/${repId}/${surpId}/ResultDiagram`}>
                <TableRow>
                    <Cell split={true} colSpan={2}><div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                        检测结果：<br/>
                        {orc?.检测结果 || '／'}
                    </div></Cell>
                </TableRow>
            </DirectLink>
        </TailMenRowIspCheck>
    </React.Fragment>;
}
